<template>
  <v-card class="mx-auto">
    <!-- 配置数据库信息-->
    <v-data-table
            :headers="headers"
            :items="db_lists"
            hide-default-footer
            sort-by="dbUrl"
            class="elevation-1">

      <!--新增按钮及新增修改弹出框-->
      <template v-slot:top>
        <v-toolbar flat color="white">
          <v-dialog v-model="dialog" max-width="500px">
            <template v-slot:activator="{ on, attrs }">
              <v-btn color="primary"
                     dark
                     class="mb-2"
                     v-bind="attrs"
                     v-on="on"
              >新增DB配置</v-btn>
            </template>

            <v-card>
              <v-card-title>
                <span class="headline">{{ formTitle }}</span>
              </v-card-title>

              <v-card-text>
                <v-container>
                  <v-form ref="dialogForm" v-model="dialogValid">

                    <v-text-field v-model="editedItem.dbName"
                                  :rules="dbNameRules"
                                  label="数据库(schema dbname 不是中文描述)"></v-text-field>

                    <v-text-field v-model="editedItem.dbUser"
                                  :rules="dbUserRules"
                                  label="数据库用户"></v-text-field>

                    <v-text-field v-model="editedItem.dbHost"
                                  :rules="dbHostRules"
                                  label="数据库IP地址"></v-text-field>

                    <v-text-field v-model="editedItem.dbPort"
                                  :rules="dbPortRules"
                                  label="数据库端口"></v-text-field>

                  </v-form>
                </v-container>
              </v-card-text>

              <v-card-actions>
                <v-spacer></v-spacer>
                <v-btn color="blue darken-1" text @click="close">取消</v-btn>
                <v-btn color="blue darken-1"  @click="save">保存</v-btn>
              </v-card-actions>
            </v-card>
          </v-dialog>
        </v-toolbar>
      </template>
      <!--每一行后面的操作按钮 -->
      <template v-slot:item.actions="{ item }">
        <v-icon small class="mr-2" @click="editItem(item)">
          mdi-pencil
        </v-icon>
        <v-icon small @click="deleteItem(item)">
          mdi-delete
        </v-icon>
        <v-btn class="mx-2" fab small dark color="primary" @click="showTableDialog(item)">
          <v-icon dark>mdi-format-list-bulleted-square</v-icon>
        </v-btn>
      </template>

      <template v-slot:no-data>
        <v-card-text>请添加数据</v-card-text>
      </template>
    </v-data-table>

    <!-- 选择配置表信息-->
    <v-dialog v-model="tableDialog" max-width="500px">
      <v-data-table
              :headers="dbTableHeaders"
              :items="dbTables"
              :single-select='false'
              item-key="tableName"
              hide-default-footer
              disable-pagination
              class="elevation-1">

        <!--每一行后面的操作按钮 -->
        <template v-slot:item.actions="{ item }">
          <v-btn color="primary" small @click="goColumnEdit(item)">
            配置代码生成信息
          </v-btn>
        </template>
      </v-data-table>
    </v-dialog>
  </v-card>
</template>

<script>
  import MySQLInfo from "../utils/mysqlinfo";

  export default {
    data: () => ({
      dialog: false,
      tableDialog: false,  //数据库表信息弹出框
      dbTables: [],     //该数据库的所有表
      dbTableHeaders: [ //数据库表Table表头
        { text: '数据库表名', value: 'tableName' },
        { text: '数据库表描述', value: 'tableComment' },
        { text: '操作', value: 'actions', sortable: false },
      ],
      dbConfig: {}, //当前正在进行表配置的数据库
      headers: [
        {
          text: '数据库名称',
          align: 'start',
          sortable: false,
          value: 'dbName',
        },
        { text: '数据库IP地址', value: 'dbHost' },
        { text: '数据库端口', value: 'dbPort' },
        { text: '数据库用户', value: 'dbUser' },
        { text: '操作', value: 'actions', sortable: false },
      ],
      db_lists: [],
      editedId: '', //默认新增数据，新增数据没有id
      editedItem: {
        id: '',
        dbHost: '',
        dbPort: '',
        dbUser: '',
        dbName: ''
      },
      defaultItem: {
        id: '',
        dbHost: '',
        dbPort: '',
        dbUser: '',
        dbName: ''
      },
      dialogValid: true,
      dbNameRules:[
        value => !!value || '请填写数据库名,不能为空',
      ],
      dbHostRules:[
        value => !!value || '请填写数据库服务IP地址,不能为空',
        value => {
          const pattern = /^((25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))$/
          return pattern.test(value) || '请输入正确的ip地址'
        },
      ],
      dbPortRules:[
        v => (v && v >=1 && v <= 65535)  || '请填写正确的数据库服务端口,不能为空',
      ],
      dbUserRules:[
        value => !!value || '请填写正确的数据库用户名,不能为空',
      ]
    }),

    computed: {
      formTitle () {
        return this.editedId === '' ? '新增数据项' : '修改数据项'
      },
    },

    watch: {
      dialog (val) {
        val || this.close()
      },
    },

    created () {
      this.initialize()
    },

    methods: {
      initialize () {
        this.db_lists = this.$db.get('db_config').value()
      },
      editItem (item) {
        this.editedId = item.id
        this.editedItem = Object.assign({}, item)
        this.dialog = true
      },

      deleteItem (item) {

        confirm('您确定要删除 ' + item.dbName + '么?')
          && this.$db.get('db_config')
                .removeById(item.id)
                .write()
        this.db_lists = this.$db.get('db_config').value()

      },
      async showTableDialog(item){
        let dbPwd = await this.$dialog.prompt({
          text: '密码',
          title: '请输入你选择的数据库的密码',
          actions:{false: '取消', true: '提交'}
        });
        if(dbPwd) {//提交有值
          this.tableDialog = true;
          this.dbConfig = item;  //保存状态，当前正在进行表配置的数据库
          this.dbConfig.dbPwd = dbPwd;
          new MySQLInfo(
                  item.dbHost,
                  item.dbPort,
                  item.dbUser,
                  dbPwd,
                  item.dbName,
          ).getTableInfo().then(results => {
            this.dbTables = results
          }).catch(error =>{
            this.$dialog.error({
              text: error,
              title: '出现错误'
            })
          })
        }
      },
      goColumnEdit(table){
        this.$router.push({ name: 'TableColumnConfig',
          params: {
            dbConfig:this.dbConfig,
            tableInfo: table
          }
        })
      },
      close () {
        this.dialog = false
        this.$nextTick(() => {
          this.$refs.dialogForm.resetValidation()
          this.editedItem = Object.assign({}, this.defaultItem)
          this.editedId = ''
        })
      },

      save () {
        if (this.editedId !== '') { //修改DB配置的数据
          this.$db.read().get("db_config")
                  .find({ id: this.editedId })
                  .assign(this.editedItem)
                  .write()
          this.db_lists = this.$db.get('db_config').value()
        } else { //新增数据
          this.db_lists.push(this.editedItem)
          this.$db.read().get("db_config").insert(this.editedItem).write()
        }
        this.close()
      },
    },
  }
</script>